<?php


namespace Appstore\Controller;

use Appstore\Model;
use Think\Controller;

class InstallController extends BaseController
{

    protected $versionModel;
    public function _initialize()
    {
        //暂不做验证
       /* if (!is_login()) {
            $this->ajaxReturn(false);
        }*/
        $this->versionModel= D('AppstoreVersion');
    }

    /**
     * 自动安装获取版本信息
     */
    public function getVersion()
    {
        //todo 绑定验证，唯一性验证
        $aToken = I('get.token', '', 'text');
        $versionModel =$this->versionModel;
        //获取版本信息，此处不将此token置为无效
        $version = $versionModel->getVersionByToken($aToken,false);
        if ($version === false) {
            $this->ajaxReturn(array('info' => $versionModel->getError(), 'status' => 0));
            exit;
        }
        $version['goods'] = D('AppstoreGoods')->getById($version['goods_id']);
        $version['goods']['cover_url']=getThumbImageById($version['goods']['cover'],120,120);
        $this->ajaxReturn(array('version' => $version, 'status' => 1));
    }

    public function getUpdateList(){
        $aToken=I('get.token','','text');
        $updateList=$this->versionModel->getUpdateListByToken($aToken);
        $this->ajaxReturn(array('updateList'=>$updateList,'status'=>1));
    }

    public function download(){
        $aType=I('get.type','get','text');
        $versionModel = D('AppstoreVersion');
        //通过安装程序下载
       $token = I('get.token', '', 'text');
        $version = $versionModel->getVersionByToken($token,null,$aType);

        if ($version['id'] == 0) {
            $this->error('版本不存在。');
        } else {
            if (intval($version['pack']) == 0) {
                $this->error('文件不存在。');
            }
            $goods = D('AppstoreGoods')->find($version['goods_id']);
            D('AppstoreVersion')->where(array('id' => intval($version['id'])))->setInc('download_count');

            D('AppstoreResource')->where(array('id' => intval($version['goods_id'])))->setInc('total_download_count');
            if (is_tip($goods['uid'])) {
                if (get_uid()) {
                    D('Common/Message')->sendMessage($goods['uid'], text($goods['title']) . '被下载', '商品——' . text($goods['title']), 'appstore/admin/myplugin', array(), is_login(), 2);
                } else {
                    D('Common/Message')->sendMessage($goods['uid'], text($goods['title']) . '被在线升级', '商品——' . text($goods['title']), 'appstore/admin/myplugin', array(), $version['uid'], 2);
                }

            }
            $fileModel = D('File');
            if ($fileModel->download(C('DOWNLOAD_UPLOAD.rootPath'), intval($version['pack'])) == false) {
                $this->error($fileModel->getError());
            };
        }

    }
}